﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Charts.Entity.Sample.Controllers
{
	public class HomeController : Controller
	{
		public ActionResult Index()
		{
			return View();
		}

		/// <summary>
		/// Summarizes items by cateogry for the donut chart
		/// </summary>
		/// <returns>JSON Array</returns>
		public JsonResult CategorySummary()
		{
			object data = null;

			using (Models.ChartsDatabaseEntities db = new Models.ChartsDatabaseEntities())
			{
				// ***
				// *** The pie chart expects an array of objects with two
				// *** elements:
				// *** label: The text displayed
				// *** value: The number that is displayed
				// ***
				var qry = from tbl1 in db.Items
						  join tbl2 in db.Categories on tbl1.CategoryId equals tbl2.CategoryId
						  group tbl1 by tbl1.CategoryId into g
						  select new
						  {
							  label = g.FirstOrDefault().Category.CategoryName,
							  value = g.Count()
						  };

				// ***
				// *** Convert the query results to an array
				// ***
				data = qry.ToArray();

			}

			return Json(data, JsonRequestBehavior.AllowGet);
		}
	}
}